package repository

import (
	"context"
	"gitee.com/jinmingzhi/cdce-service/internal/model"
	"gitee.com/jinmingzhi/kit/rdb"
)

const (
	payAddField         = "uid, pay_num, school_time, batch_id, amount, status, create_time"
	payField            = "id, uid, pay_num, school_time, batch_id, amount, status, create_time"
	payAddOne           = "insert into `" + PAY + "`(" + payAddField + ") values(?,?,?,?,?,?,?)"
	payConfirmCost      = "update `" + PAY + "` set status=? where id=? and uid = ?"
	payFindAllFiled     = "`" + PAY + "`.id, `" + PAY + "`.uid, `" + PAY + "`.pay_num, `" + PAY + "`.school_time, `" + BATCHTIME + "`.batch_name, `" + PAY + "`.amount, `" + PAY + "`.status, `" + PAY + "`.create_time"
	payFindAllSql       = "select " + payFindAllFiled + " from `" + PAY + "` left join `" + BATCHTIME + "` on `" + PAY + "`.batch_id = `" + BATCHTIME + "`.id  where uid=? and `" + PAY + "`.status =?"
	payStatusFindAllSql = "select " + payFindAllFiled + " from `" + PAY + "` left join `" + BATCHTIME + "` on `" + PAY + "`.batch_id = `" + BATCHTIME + "`.id  where uid=? and `" + PAY + "`.status =?"
)

type Pay interface {
	AddOne(ctx context.Context, data *model.Pay) error
	ConfirmCost(ctx context.Context, pid, uid uint32) error
	FindAllByUid(ctx context.Context, uid uint32) ([]*model.PayList, error)
	FindAllByUidStatus(ctx context.Context, uid uint32, status bool) ([]*model.PayList, error)
}

type PayImpl struct {
	repo rdb.Repository
}

func NewPay(repo rdb.Repository) Pay {
	return &PayImpl{repo: repo}
}

func (p *PayImpl) AddOne(ctx context.Context, data *model.Pay) error {
	_, err := p.repo.AddOne(ctx, payAddOne, data.UID, data.PayNum, data.SchoolTime, data.BatchID, data.Amount, data.Status, data.CreateTime)
	if err != nil {
		return err
	}
	return nil
}

func (p *PayImpl) ConfirmCost(ctx context.Context, pid, uid uint32) error {
	return p.repo.SaveOne(ctx, payConfirmCost, true, pid, uid)
}

func (p *PayImpl) FindAllByUid(ctx context.Context, uid uint32) ([]*model.PayList, error) {
	data := []*model.PayList{}
	err := p.repo.FindAll(ctx, &data, payFindAllSql, uid, false)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (p *PayImpl) FindAllByUidStatus(ctx context.Context, uid uint32, status bool) ([]*model.PayList, error) {
	data := []*model.PayList{}
	var res uint32
	if status {
		res = 1
	}
	err := p.repo.FindAll(ctx, &data, payStatusFindAllSql, uid, res)
	if err != nil {
		return nil, err
	}
	return data, nil
}
